#include "timeout.h"
#include <sys/time.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>

struct timeout timer[1];

unsigned long long createTime() {
  struct timeval tv;
  struct timezone tz;
  struct tm *tm;

  gettimeofday(&tv, &tz);
  tm=localtime(&tv.tv_sec);
  unsigned long long time;
  time = (tm->tm_hour * 3600) + (tm->tm_min * 60) + tm->tm_sec;
  time = (time * 1000000) + tv.tv_usec;

  return time;
}

void addTimeout(int seqn) {
  if(timer[0].sequence == seqn) {
    timer[0].timeSent = createTime();
    timer[0].requestsSent++;
  }
  else {
    timer[0].sequence = seqn;
    timer[0].timeSent = createTime();
    timer[0].requestsSent = 1;
  }
}

void removeTimeout() {
  timer[0].sequence = -1;
}

//change this to void *timeThread()
void main() {
  int i = 1;
  addTimeout(i);
  printf("added:\n\tsequence number: %d\n\ttime sent: %lld\n\trequests sent: %d\n\n", timer[0].sequence, timer[0].timeSent, timer[0].requestsSent);
  int initialTime = createTime();
  long waitTime = 3000000;
  while(1) {
    int count = 0;
    unsigned long long timesec;
    timesec = createTime();

    if((timesec - timer[0].timeSent) >= waitTime) {
      if(timer[0].requestsSent < 5) {
	//send packet
	addTimeout(timer[0].sequence);
	printf("added:\n\tsequence number: %d\n\ttime sent: %lld\n\trequests sent: %d\n\n", timer[0].sequence, timer[0].timeSent, timer[0].requestsSent);
      }
      else {
	removeTimeout();
	addTimeout(++i);
        printf("added:\n\tsequence number: %d\n\ttime sent: %lld\n\trequests sent: %d\n\n", timer[0].sequence, timer[0].timeSent, timer[0].requestsSent);
      }
    }
  }
}
